package com.cskaoyan.login;

import com.cskaoyan.jdbc.util.JDBCUtils;

import java.sql.*;

/**
 * 创建日期: 2022/06/02 11:40
 *
 * @author ciggar
 *
 * 登录的案例
 */
public class LoginDemo {


    public static void main(String[] args) throws SQLException {

//        // 正常的输入
//        Boolean ret1 = login("changfeng", "nvzhuang");
//
//        // 非法的输入
//        Boolean ret2 = login("changfeng", "xxx' or '1=1");


//        Boolean ret = loginUsePrepareStatement("changfeng", "nvzhuang");
        Boolean ret = loginUsePrepareStatement("changfeng", "xxx' or '1=1");

        if (ret){
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");
        }

    }



    /**
     * 创建日期：2022/06/02 11:41
     * @param username  用户名
     * @param password  密码
     * @return java.lang.Boolean 登录成功：true  登录失败：false
     * @author ciggar
     * 登录的方法 -- 使用Statement
     */
    public static Boolean login(String username,String password) throws SQLException {

        // 获取连接
        Connection connection = JDBCUtils.getConnection();

        // 获取statement
        Statement statement = connection.createStatement();

        // 执行SQL语句
        String sql = "select * from account where username = '"+username+"' and password ='" + password+"'";
        System.out.println("sql:" + sql);

        ResultSet resultSet = statement.executeQuery(sql);

        if (resultSet.next()) {
            return true;
        }else {
            return false;
        }

    }



    /**
     * 创建日期：2022/06/02 11:41
     * @param username  用户名
     * @param password  密码
     * @return java.lang.Boolean 登录成功：true  登录失败：false
     * @author ciggar
     * 登录的方法 -- 使用PreparedStatement
     */
    public static Boolean loginUsePrepareStatement(String username,String password) throws SQLException {

        boolean ret = false;

        // 获取连接
        Connection connection = JDBCUtils.getConnection();

        String sql = "select * from account where username = ? and password = ?";
        // 获取PreparedStatement
        // 把这个SQL语句会传递给MySQL服务器，然后MySQL服务器会对这个SQL语句进行预编译，编译成MySQL可以执行的命令
        // 后续再传递过来的 参数就不会再进行编译了，会被MySQL直接当成字符串 或者是 参数来处理
        PreparedStatement preparedStatement = connection.prepareStatement(sql);


        // 设置参数
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);

        // 传递参数，执行SQL语句
        ResultSet resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            ret = true;

            int id = resultSet.getInt("id");
            String username1 = resultSet.getString("username");
            String password1 = resultSet.getString("password");

            System.out.println("id:" + id  +", username:" + username1 + ", password:" + password1);
        }

        return ret;

    }
}
